package com.chinameyer.workorders.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.chinameyer.workorders.bean.MeyerWorkOrders;
import com.chinameyer.workorders.dto.orders.AddWorkOrdersDTO;
import com.chinameyer.workorders.service.WorkOrderService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class ExcelReadUtil extends AnalysisEventListener<MeyerWorkOrders> {

    private WorkOrderService workOrderService;
    private int catalogueId;
    /**
     * 每隔5条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<MeyerWorkOrders> list = new ArrayList<>();

    public ExcelReadUtil(WorkOrderService workOrderService,int catalogueId) {
        this.workOrderService = workOrderService;
        this.catalogueId = catalogueId;
    }

    @Override
    public void invoke(MeyerWorkOrders workOrders, AnalysisContext analysisContext) {
        list.add(workOrders);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        for (MeyerWorkOrders workOrders:list) {
            AddWorkOrdersDTO addWorkOrdersDTO = new AddWorkOrdersDTO();
            BeanUtils.copyProperties(workOrders, addWorkOrdersDTO);
            addWorkOrdersDTO.setCatalogueId(catalogueId);
            workOrderService.addOrders(addWorkOrdersDTO);
        }
    }

}
